#!/bin/bash

echo -e "\n==> EXECUTING @$(date -u +'%Y-%m-%d_%H-%M-%S'): ${0} $@\n"

declare _mydir=$(dirname $0)
source "${_mydir}"/env.rc
source "${_mydir}"/util.rc

main() {
    local params=$@
    local now
    local version_sticker
    local -i exit_code=0

    local should_build=${FORCE_BUILDING:-0}
    local build_prohibited=${PROHIBIT_BUILDING}
    local cache_script="cache"

    ### helper image will be also used as a cache and therefore it must not use a tag
    local helper_image="${DOCKER_REPO}"_"${DOCKER_TAG}${helper_suffix}"

    ### refresh local cache
    "${_mydir}/${cache_script}" "${_branch}" "${_blend}"
    exit_code=$?
    if [[ ${exit_code} -ne 0 ]]; then
        die "Script '${cache_script}' failed with code ${exit_code}." ${exit_code}
    fi

    echo -e "\nRemoving helper files\n"
    cleanup_scrap_files

    ### check for the '--target' parameter
    if [[ $# -gt 0 ]]; then

        ### no quotes around 'params'
        for i in ${params}; do
            if [[ "${i}" == "--target" ]]; then

                target_stage="${i}"

            elif [[ -n "${target_stage}" ]]; then

                ### only if '--target' is followed by a value
                if [[ ! "${i}" =~ ^- ]]; then

                    ### remove the '--target' with its value
                    params="${params/--target ${i}/}"
                fi
                break
            fi
        done

        ### remove the orphaned '--target' (missing value)
        if [[ "${target_stage}" == "--target" ]]; then
            params="${params/--target/}"
            target_stage=""
        fi
    fi

    ### build a temporary helper image for getting the current version sticker values

    ### no quotes around ${params}!
    set -x
    docker build ${params} \
        -f "${DOCKERFILE_PATH}" \
        --build-arg BASEIMAGE="${BASEIMAGE}" \
        --build-arg BASETAG="${BASETAG}" \
        \
        ${FEATURES_BUILD_SLIM:+--build-arg ARG_APT_NO_RECOMMENDS=1} \
        ${FEATURES_OVERRIDING_ENVV:+--build-arg ARG_FEATURES_OVERRIDING_ENVV=1} \
        ${FEATURES_SCREENSHOOTING:+--build-arg ARG_FEATURES_SCREENSHOOTING=1} \
        ${FEATURES_THUMBNAILING:+--build-arg ARG_FEATURES_THUMBNAILING=1} \
        \
        ${FEATURES_VNC:+--build-arg ARG_TIGERVNC_DISTRO=${TIGERVNC_DISTRO}} \
        ${FEATURES_VNC:+--build-arg ARG_TIGERVNC_VERSION=${TIGERVNC_VERSION}} \
        \
        ${FEATURES_NOVNC:+--build-arg ARG_NOVNC_VERSION=${NOVNC_VERSION}} \
        ${FEATURES_NOVNC:+--build-arg ARG_WEBSOCKIFY_VERSION=${WEBSOCKIFY_VERSION}} \
        ${FEATURES_NOVNC:+--build-arg ARG_MERGE_STAGE_VNC_BASE="stage_novnc"} \
        \
        ${FEATURES_CHROMIUM:+--build-arg ARG_CHROMIUM_DISTRO=${CHROMIUM_DISTRO}} \
        ${FEATURES_CHROMIUM:+--build-arg ARG_CHROMIUM_VERSION=${CHROMIUM_VERSION}} \
        ${FEATURES_CHROMIUM:+--build-arg ARG_MERGE_STAGE_BROWSER_BASE="stage_chromium"} \
        \
        ${FEATURES_FIREFOX:+--build-arg ARG_MERGE_STAGE_BROWSER_BASE="stage_firefox"} \
        ${FEATURES_FIREFOX_PLUS:+--build-arg ARG_MERGE_STAGE_BROWSER_BASE="stage_firefox_plus"} \
        \
        -t "${helper_image}" "${_build_context}"

    exit_code=$?
    set +x

    if [[ ${exit_code} -ne 0 ]]; then
        set +x

        die "Failed to build helper image '${helper_image}'" ${exit_code}
    fi

    ### get the actual verbose version sticker value from the helper image and store it as the current one
    ### note that some apps require display to report their versions correctly (e.g. Ristretto or Screenshooter)
    version_sticker="$(docker run --rm ${helper_image} --version-sticker-verbose)"
    echo "${version_sticker}" >"${_build_context}/${_scrap_version_sticker_verbose_current}"
    echo -e "Current verbose version sticker:\n$(cat ${_build_context}/${_scrap_version_sticker_verbose_current})"

    if [[ "${should_build}" == "1" ]]; then

        echo
        echo "Building of new image has been forced."
    else
        echo
        echo "Building of new image has not been forced."

        echo "Getting the previous verbose version sticker value from the builder gist '${GIST_ID}'"
        if [[ -n "${GIST_ID}" ]]; then

            get_gist_file "${GIST_ID}" "${DOCKER_REPO}" "${DOCKER_TAG}" "version-sticker-verbose.txt" "${_build_context}/${_scrap_version_sticker_verbose_previous}"
        else
            ### create an empty file instead
            echo -n "" >"${_build_context}/${_scrap_version_sticker_verbose_previous}"
        fi

        echo "Comparing verbose version stickers"
        if cmp -s "${_build_context}/${_scrap_version_sticker_verbose_current}" "${_build_context}/${_scrap_version_sticker_verbose_previous}"; then

            ### verbose version sticker hasn't changed since the last build - stop building
            echo "Verbose version sticker has not changed since the last build, no need for building and deploying a new image."
            echo

            ### if this file is present, the building will not continue
            echo "Demanding building stop"
            touch "${_build_context}/${_scrap_demand_stop_building}"

        else
            ### verbose version sticker has changed since the last build - a new image should be built
            echo "Verbose version sticker has changed, a new image should be built and deployed."
            should_build="1"
        fi
    fi

    ### get also the actual short version sticker value from the helper image and store it as the current one
    ### note that some apps require display to report their versions correctly (e.g. Ristretto or Screenshooter)
    version_sticker="$(docker run --rm ${helper_image} --version-sticker)"

    ### save the current short version sticker in any case
    ### this allows to delete the blocking file manually and continue building
    ### metadata label value 'any.accetto.version-sticker' is filled from this file
    echo -n "${VERSION_STICKER_PREFIX}${version_sticker}${VERSION_STICKER_SUFFIX}" >"${_build_context}/${_scrap_version_sticker_current}"

    ### building prohibited by environment variable
    ### useful for testing the autobuilding on DockerHub before release
    if [[ "${should_build}" == "1" && "${build_prohibited}" == "1" ]]; then

        ### if this file is present, the building will not continue
        echo "Building has been prohibited. Demanding building stop"
        echo
        touch "${_build_context}/${_scrap_demand_stop_building}"
    fi

    ### display the actual short version sticker
    echo "Current version sticker of '${helper_image}': ${VERSION_STICKER_PREFIX}${version_sticker}${VERSION_STICKER_SUFFIX}"

    ### moved to the 'build' script where the helper image is used as a cache
    ### however, there could be also no 'build' call
    if [[ -f "${_build_context}/${_scrap_demand_stop_building}" ]]; then
        echo; echo "Removing helper image because no 'build' is needed"
        docker rmi "${helper_image}"
    fi
}

main $@

echo -e "\n==> FINISHED  @$(date -u +'%Y-%m-%d_%H-%M-%S'): ${0} $@\n"
